package hr.ctg.domain.action;

import hr.ctg.SystemException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.jboss.seam.Component;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.cache.CacheProvider;
import org.jboss.seam.international.LocaleSelector;
import org.jboss.seam.log.Log;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

@Name("newsAction")
public class NewsAction {
	@Logger
	Log log;

	@SuppressWarnings("unchecked")
	@Factory("news")
	public String getNews() {
		final CacheProvider cacheProvider = (CacheProvider) Component
				.getInstance(CacheProvider.class);
		final LocaleSelector ls = (LocaleSelector) Component
				.getInstance(LocaleSelector.class);
		String news = (String) cacheProvider.get("news", "home");
		if (news == null) {
			try {
				final URL ctg = new URL(
						"http://www.crotouristguide.com/portal/c/journal/get_articles?templateId=10242&amp;languageId="
								+ ls.getLocaleString()
								+ "&amp;orderByCol=display-date&amp;delta=3");
				final BufferedReader in = new BufferedReader(
						new InputStreamReader(ctg.openStream()));

				String inputLine;
				final StringWriter out = new StringWriter();
				while ((inputLine = in.readLine()) != null)
					out.write(inputLine);
				news = createNews(out.toString());
				in.close();
				out.close();
			} catch (final MalformedURLException e) {
				throw new SystemException(e);
			} catch (final IOException e) {
				throw new SystemException(e);
			}

			cacheProvider.put("news", "home", news);
		}
		return news;
	}

	private String createNews(final String xml) {
		final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		Document doc = null;
		try {
			final DocumentBuilder db = dbf.newDocumentBuilder();
			doc = db.parse(xml);
		} catch (final ParserConfigurationException e) {
			throw new SystemException(e);
		} catch (final SAXException e) {
			throw new SystemException(e);
		} catch (final IOException e) {
			throw new SystemException(e);
		}

		doc.getDocumentElement().normalize();
		log.debug("Root element " + doc.getDocumentElement().getNodeName());
		final NodeList nodeLst = doc.getElementsByTagName("result");
		final StringBuffer resultHTML = new StringBuffer();
		int validCnt = 0;
		for (int s = 0; s < nodeLst.getLength(); s++) {
			Node fstNode = nodeLst.item(s);
			if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
				Element fstElmnt = (Element) fstNode;
				final NodeList elems = fstElmnt
						.getElementsByTagName("dynamic-element");
				String title = "";
				String body = "";
				String image = "";
				@SuppressWarnings("unused")
				String displayDate = "";
				for (int i = 0; i < elems.getLength(); i++) {
					fstNode = elems.item(s);
					if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
						fstElmnt = (Element) fstNode;
						final String atri = fstElmnt.getAttribute("name");
						final NodeList fstNmElmntLst = fstElmnt
								.getElementsByTagName("dynamic-content");
						final Element fstNmElmnt = (Element) fstNmElmntLst
								.item(0);
						final NodeList fstNm = fstNmElmnt.getChildNodes();
						if (atri == "title") {
							title = fstNm.item(0).getNodeValue();
							continue;
						}
						if (atri == "image") {
							image = fstNm.item(0).getNodeValue();
							continue;
						}
						if (atri == "body") {
							body = fstNm.item(0).getNodeValue();
							continue;
						}
						if (atri == "reserved-article-display-date") {
							displayDate = fstNm.item(0).getNodeValue();
							continue;
						}
					}
				}

				if (image.length() == 0)
					continue;
				final String imageTag = getImageTag(image);
				if (body.length() > 170)
					body = body.substring(0, 170) + "...";
				resultHTML
						.append("<div style='float: left; width:120px;'><span>"
								+ title + "</span>" + imageTag + body
								+ "</div>");
				if (++validCnt == 4)
					break;
			}

		}
		return resultHTML.toString();
	}

	private String getImageTag(final String image) {
		if (image.length() < 1)
			return "";
		String imgUrl = image;
		if (image.indexOf("@image_path@") != -1
				&& image.indexOf("@group_id@") != -1) {
			imgUrl = "/portal/image"
					+ image.substring("@image_path@".length(), image
							.indexOf("@group_id@")) + "273"
					+ image.substring(image.lastIndexOf("@"));
			// imgUrl =
			// "/image"+image.substring("@image_path@".length,image.indexOf("@group_id@"))+"273"+image.substring(image.lastIndexOf("@"));
		} else if (image.indexOf("@image_path@") != -1) {
			imgUrl = "/portal/image" + image.substring("@image_path@".length());
			// imgUrl = "/image"+image.substring("@image_path@".length);
		} else if (image.indexOf("@group_id@") != -1) {
			imgUrl = "/portal/"
					+ image.substring(image.indexOf("@group_id@"), "@group_id@"
							.length() - 1) + "273"
					+ image.substring(image.lastIndexOf("@"));
			// imgUrl =
			// "/"+image.substring(image.indexOf("@group_id@"),"@group_id@".length-1)+"273"+image.substring(image.lastIndexOf("@"));
		}
		return "<img src='" + imgUrl
				+ "' style='margin-right: 5px; width:100px;'/>";
	}

}
